﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace FlashPay.Service.Impl
{
    using FlashPay.DAO.Interface;
    using FlashPay.Entity.Enum;
    using FlashPay.Service.Interface;


    public class AuthServiceImpl: AuthService
    {
        /// <summary>
        /// 授权数据接口
        /// </summary>
        private readonly AuthorizeDao _authorizeDao;

        /// <summary>
        /// 功能权限数据接口
        /// </summary>
        private readonly PermissionDao _permissionDao;

        /// <summary>
        /// 用户数据接口
        /// </summary>
        private readonly UserInfoDao _userInfoDao;


        public AuthServiceImpl(AuthorizeDao authorizeDao, PermissionDao permissionDao, UserInfoDao userInfoDao)
        {
            this._authorizeDao = authorizeDao;
            this._permissionDao = permissionDao;
            this._userInfoDao = userInfoDao;
        }

        /// <summary>
        /// 查询用户是否包含code权限
        /// </summary>
        /// <param name="userId">用户编号</param>
        /// <param name="code">权限码</param>
        /// <returns></returns>
        public bool IsAuthority(int userId, string code) {

            var result = false;

            try
            {
                var user = _userInfoDao.Get(userId);
                if (user == null) {
                    throw new Exception("用户不存在!");
                }

                var authorizes = _authorizeDao.GetList(new Entity.Parameter.AuthorizeQuery()
                {
                    UserSysNo = user.UId,
                    RoleStatus = RoleStatus.显示.GetHashCode(),
                    AuthorizeType = AuthorizeType.权限.GetHashCode()
                });

                if (authorizes == null && authorizes.Count <= 0) {
                    throw new Exception("无此权限！");
                }

                var permissions = _permissionDao.GetListByIds(authorizes.Select(p => p.AuthPid).Distinct().ToList());
                if (permissions.Any()) {
                    var permissionsCode = permissions.Where(x => x.Hide == PermissionStatus.显示.GetHashCode()).Select(p => p.PCode).ToList();
                    if (permissionsCode.Contains(code)) {
                        result = true;
                        return result;
                    }
                }
            }
            catch (Exception ex) {
                throw new Exception(ex.Message);
            }

            return result;
        }
    }
}
